package model;

import java.util.LinkedList;

import observer.IExchangerObserver;

public class Exchanger implements IExchangerModel {
	private LinkedList<Currency> currencies = new LinkedList<Currency>();
	private IExchangerObserver observer;

	public Exchanger() {
		super();
		currencies.add(new Currency("euro", "EUR", 1.23, null));
		currencies.add(new Currency("dollar", "USD", 1, null));
	}

	@Override
	public void modifyRate(String currencyName, double value) {
		seek:for(Currency currency : this.currencies){
			if(currency.getCurrencyName().equals(currencyName)){
				currency.setRate(value);
				break seek;
			}
		}
		observer.rateChanged();
	}

	@Override
	public double obtainRate(String currencyName) {
		for(Currency currency : this.currencies){
			if(currency.getCurrencyName().equals(currencyName)){
				return currency.getRate();
			}
		}
		return 0; //TODO
	}

	@Override
	public void addCurrency(String currencyName, String currencyAbreviation,
			double rate, String iconPath) {
		this.currencies.add(new Currency(currencyName, currencyAbreviation, rate, iconPath));
		observer.currencyAdded();
	}

	@Override
	public void removeCurrency(String currencyName) {
		int index = 0;
		seek:for(int i=0; i<this.currencies.size(); i++){
			if(currencies.get(i).getCurrencyName().equals(currencyName)){
				index = i;
				break seek;
			}
		}
		this.currencies.remove(index);
		observer.currencyRemoved();
	}
	
	public void removeAllCurrencies(){
		this.currencies.removeAll(currencies);
		observer.currencyRemoved();
	}

	@Override
	public String[] getAllCurrenciesNames() {
		String currenciesNames[] = new String[this.currencies.size()];
		int i = 0;
		for(Currency currency : this.currencies){
			currenciesNames[i++] = currency.getCurrencyName();
		}
		return currenciesNames;
	}

	@Override
	public void setObserver(IExchangerObserver observer) {
		this.observer = observer;	
	}

	@Override
	public String[][] getAllCurrenciesInfos() {
		String currenciesInfos[][] = new String[this.currencies.size()][4];
		int i = 0;
		for(Currency currency : this.currencies){
			currenciesInfos[i][0] = currency.getIconPath();
			currenciesInfos[i][1] = currency.getCurrencyName();
			currenciesInfos[i][2] = currency.getCurrencyAbreviation();
			currenciesInfos[i][3] = ""+currency.getRate();
			i++;
		}
		return currenciesInfos;
	}
	
	@Override
	public String[][] getAllCurrenciesNamesWithIconPath() {
		String namesAndIconPath[][] = new String[this.currencies.size()][2];
		int i = 0;
		for(Currency currency : this.currencies){
			namesAndIconPath[i][0] = currency.getCurrencyName();
			namesAndIconPath[i][1] = currency.getIconPath();
			i++;
		}
		return namesAndIconPath;
	}
}
